package com.yxt.qmgf.klotski.service;

import com.yxt.qmgf.userinfo.vo.UserInfoVO;
import com.yxt.qmgf.klotski.vo.ScoreRecord;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ScoreService {
    private static final String SCORE_FILE = "scores.dat";

    // 保存分数记录
    public void saveScore(UserInfoVO user, int size, int moves) {
        List<ScoreRecord> records = loadScores();

        // 计算积分 (简单的算法: 难度系数 * (1000 - 步数))
        int difficultyFactor = size * 100;
        int score = difficultyFactor * (1000 - Math.min(moves, 1000)) / 100;

        ScoreRecord newRecord = new ScoreRecord(
                user.getUsername(),
                user.getName(),
                size,
                moves,
                score,
                System.currentTimeMillis()
        );

        records.add(newRecord);

        // 保存到文件
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(SCORE_FILE))) {
            oos.writeObject(records);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 加载所有分数记录
    @SuppressWarnings("unchecked")
    public List<ScoreRecord> loadScores() {
        File file = new File(SCORE_FILE);
        if (!file.exists()) {
            return new ArrayList<>();
        }

        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(SCORE_FILE))) {
            return (List<ScoreRecord>) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return new ArrayList<>();
        }
    }

    // 获取当前用户的分数记录
    public List<ScoreRecord> getUserScores(String userId) {
        List<ScoreRecord> allRecords = loadScores();
        List<ScoreRecord> userRecords = new ArrayList<>();

        for (ScoreRecord record : allRecords) {
            if (record.getUserId().equals(userId)) {
                userRecords.add(record);
            }
        }

        // 按分数降序排序
        userRecords.sort((r1, r2) -> Integer.compare(r2.getScore(), r1.getScore()));

        return userRecords;
    }

    // 获取排行榜
    public List<ScoreRecord> getScoreboard() {
        List<ScoreRecord> allRecords = loadScores();

        // 按分数降序排序
        allRecords.sort((r1, r2) -> Integer.compare(r2.getScore(), r1.getScore()));

        // 只返回前100名
        return allRecords.subList(0, Math.min(allRecords.size(), 100));
    }
}